<%@ page import="com.example.util.DBUtil" %>
<%@ page import="com.example.domain.User" %>
<%@ page import="java.sql.*" %>
<%@ page contentType="application/json;charset=UTF-8" language="java" %>
<%
    // 检查用户是否已登录
    User currentUser = (User) session.getAttribute("user");
    if (currentUser == null) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        out.print("{\"success\": false, \"message\": \"未登录\"}");
        return;
    }
    
    Connection conn = null;
    PreparedStatement productStmt = null;
    PreparedStatement updateStmt = null;
    PreparedStatement deleteStmt = null;
    ResultSet productRs = null;
    
    try {
        // 获取参数
        String productIdStr = request.getParameter("productId");
        String quantityStr = request.getParameter("quantity");
        
        if (productIdStr == null || productIdStr.trim().isEmpty()) {
            out.print("{\"success\": false, \"message\": \"商品ID不能为空\"}");
            return;
        }
        
        if (quantityStr == null || quantityStr.trim().isEmpty()) {
            out.print("{\"success\": false, \"message\": \"数量不能为空\"}");
            return;
        }
        
        int productId = Integer.parseInt(productIdStr);
        int quantity = Integer.parseInt(quantityStr);
        
        conn = DBUtil.getConnection();
        conn.setAutoCommit(false); // 开启事务
        
        // 如果数量小于等于0，则从购物车中删除该商品
        if (quantity <= 0) {
            String deleteSql = "DELETE FROM tb_cart WHERE member_id = ? AND product_id = ?";
            deleteStmt = conn.prepareStatement(deleteSql);
            deleteStmt.setInt(1, currentUser.getId());
            deleteStmt.setInt(2, productId);
            
            int rowsAffected = deleteStmt.executeUpdate();
            if (rowsAffected > 0) {
                conn.commit(); // 提交事务
                out.print("{\"success\": true, \"message\": \"商品已从购物车中删除\", \"removed\": true}");
            } else {
                conn.rollback();
                out.print("{\"success\": false, \"message\": \"删除失败: 未找到匹配的购物车记录\"}");
            }
            return;
        }
        
        // 获取产品价格信息
        String productSql = "SELECT price, sale_price FROM tb_product WHERE id = ?";
        productStmt = conn.prepareStatement(productSql);
        productStmt.setInt(1, productId);
        productRs = productStmt.executeQuery();
        
        if (!productRs.next()) {
            conn.rollback();
            out.print("{\"success\": false, \"message\": \"商品不存在\"}");
            return;
        }
        
        double price = productRs.getDouble("price");
        double salePrice = productRs.getDouble("sale_price");
        double productPrice = (salePrice > 0) ? salePrice : price;
        
        // 更新购物车中的商品数量和总金额
        String updateSql = "UPDATE tb_cart SET sale_num = ?, sale_price = ?, sale_money = ?, updated_at = CURRENT_TIMESTAMP WHERE member_id = ? AND product_id = ?";
        updateStmt = conn.prepareStatement(updateSql);
        updateStmt.setInt(1, quantity);
        updateStmt.setDouble(2, productPrice);
        updateStmt.setDouble(3, productPrice * quantity);
        updateStmt.setInt(4, currentUser.getId());
        updateStmt.setInt(5, productId);
        
        int rowsAffected = updateStmt.executeUpdate();
        if (rowsAffected > 0) {
            conn.commit(); // 提交事务
            // 返回JSON格式的成功响应，包含更新后的数据
            out.print("{\"success\": true, \"message\": \"更新成功\", \"quantity\": " + quantity + ", \"unitPrice\": " + productPrice + ", \"subtotal\": " + (productPrice * quantity) + "}");
        } else {
            conn.rollback();
            out.print("{\"success\": false, \"message\": \"更新失败: 未找到匹配的购物车记录\"}");
        }
    } catch (Exception e) {
        // 回滚事务
        if (conn != null) {
            try {
                conn.rollback();
            } catch (SQLException se) {
                // 忽略回滚异常
            }
        }
        out.print("{\"success\": false, \"message\": \"错误: " + e.getMessage() + "\"}");
    } finally {
        // 关闭数据库资源
        try {
            if (productRs != null) productRs.close();
            if (productStmt != null) productStmt.close();
            if (updateStmt != null) updateStmt.close();
            if (deleteStmt != null) deleteStmt.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            // 忽略关闭连接的异常
        }
    }
%>